package org.example.App;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

public class HtmlServer implements HttpHandler {
    static {
        System.out.println("html文件位置" + initFile.getHtmlFile()+ "/" + initFile.getHtmlName());
    }

    @Override
    public void handle(HttpExchange t) throws IOException {
        // 初始化文件
        File htmlFile = new File(initFile.getHtmlFile() + "/" + initFile.getHtmlName());
        // 读取文件内容并发送给客户端
        if (htmlFile.exists()) {
            t.sendResponseHeaders(200, htmlFile.length());
            OutputStream os = t.getResponseBody();
            FileInputStream fis = new FileInputStream(htmlFile);
            byte[] buffer = new byte[1024];
            int read;
            while ((read = fis.read(buffer)) != -1) {
                os.write(buffer, 0, read);
            }
            os.close();
            fis.close();
        } else {
            System.out.println("404 未找到文件");
            t.sendResponseHeaders(404, -1); // 404 Not Found
        }
    }
}